package com.iot.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iot.core.JsonHelper;
import com.iot.core.LResult;
import com.iot.core.PageData;
import com.iot.pojo.MTemp;
import com.iot.pojo.MTwork;
import com.iot.service.TempService;
import com.iot.service.TworkService;
import com.iot.util.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/work/work/")
public class TWorkController extends BaseController {
    @Autowired
    private TworkService service;
    @Autowired
    private TempService empService;

    @ResponseBody
    @RequestMapping("save")
    public String save(@RequestParam String bean) {
        try {

            MTwork entity = JsonHelper.toBean(bean, MTwork.class);
            if (entity.getWORK_ID() > 0) {
                service.update(entity);
            } else {
                entity.setWORK_NO(Common.getWorkNo());
                entity.setWORK_STATUS_ID(1);
                service.insert(entity);

            }
            return LResult.Success(entity.getWORK_ID()).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("get")
    public String getByid(@RequestParam Integer id) {
        try {
            //  String menu = request.getParameter("menu");
            MTwork bean = service.single(id);
            return LResult.Success(bean).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("del")
    public String deleteByid(@RequestParam Integer id) {
        try {
            //  String menu = request.getParameter("menu");
            service.deleteById(id);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("query")
    public String queryData() {

        try {
            PageData map = getPageData();
            if (!map.containsKey("appId")) {
                map.put("appId", 0);
            }
            if (!map.containsKey("workNo")) {
                map.put("workNo", "");
            }
            if (!map.containsKey("sdate")) {
                map.put("sdate", "");
            }
            if (!map.containsKey("edate")) {
                map.put("edate", "");
            } else {
                String strSdate = map.get("edate").toString();
                if (strSdate != "") {
                    String tempdate = Common.getShortDate(Common.getSomeDay(strSdate, 1));
                    map.put("edate", tempdate);
                }
            }
            if (!map.containsKey("workTypeId")) {
                map.put("workTypeId", 0);
            }
            if (!map.containsKey("workStatusId")) {
                map.put("workStatusId", 0);
            }

            PageHelper.startPage(Common.toInt(map.get("page")), Common.toInt(map.get("limit")));
            List<Map<String, Object>> list = service.fetchByPage(map);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            return LResult.Success(pageInfo.getTotal(), pageInfo.getList()).toJson();
        } catch (Exception ex) {
            return LResult.Error("数据错误").toJson();
        }
    }

    @ResponseBody
    @RequestMapping("getWorkByEmpId")
    public String getWorkByEmpId() {
        try {
            PageData map = getPageData();
            if (!map.containsKey("empId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("workStatusId")) {
                map.put("workStatusId", 0);
            }
            PageHelper.startPage(Common.toInt(map.get("page")), Common.toInt(map.get("limit")));
            List<Map<String, Object>> list = service.getWorkByEmpId(map);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            return LResult.Success(pageInfo.getTotal(), pageInfo.getList()).toJson();

        } catch (Exception ex) {
            return LResult.Error("数据错误").toJson();
        }
    }

    @ResponseBody
    @RequestMapping(value = "getWorkByWorkId")
    public String getWorkByWorkId() {

        try {
            PageData map = getPageData();
            if (!map.containsKey("workId")) {
                throw new Exception("缺少必要参数！");
            }

            List<Map<String, Object>> list = service.getWorkByWorkId(map);
            Integer count = list.size();
            return LResult.Success(count, list).toJson();
        } catch (Exception ex) {
            return LResult.Error("数据错误").toJson();
        }
    }

    @ResponseBody
    @RequestMapping(value = "getWorkByWorkId2")
    public String getWorkByWorkId2() {

        try {
            PageData map = getPageData();
            if (!map.containsKey("workId")) {
                throw new Exception("缺少必要参数！");
            }

            List<Map<String, Object>> list = service.getWorkByWorkId(map);
            Integer count = list.size();
            if (count >= 1) {
                return LResult.Success(list.get(0)).toJson();

            } else {
                return LResult.Success().toJson();
            }

        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("saveWorkZd")
    public String saveWorkZd() {

        try {
            //  String menu = request.getParameter("menu");
            PageData map = getPageData();
            if (!map.containsKey("workId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("handleDesc")) {
                throw new Exception("缺少必要参数！");
            }
            service.saveWorkZd(map);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }

    }

    @ResponseBody
    @RequestMapping("saveWorkJd")
    public String saveWorkJd() {
        try {
            //  String menu = request.getParameter("menu");
            PageData map = getPageData();
            if (!map.containsKey("workId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("handleDesc")) {
                throw new Exception("缺少必要参数！");
            }
            service.saveWorkJd(map);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("SaveWorkSP")
    public String SaveWorkSP() {

        try {
            //  String menu = request.getParameter("menu");
            PageData map = getPageData();
            if (!map.containsKey("workId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("resDesc")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("workStatusId")) {
                throw new Exception("缺少必要参数！");
            }
            service.SaveWorkSP(map);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("SaveWorkZdSP")
    public String SaveWorkZdSP() {
        try {
            //  String menu = request.getParameter("menu");
            PageData map = getPageData();
//            map.put("workId", 1);
//            map.put("resDesc", "cs");
//            map.put("sdate","2018-11-05");
//            map.put("deptId", 1);
//            map.put("empId", 1);
            if (!map.containsKey("workId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("resDesc")) {
                throw new Exception("缺少必要参数！");
            }
//            if (!map.containsKey("workStatusId")) {
//                throw new Exception("缺少必要参数！");
//            }
            if (!map.containsKey("sdate")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("deptId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("empId")) {
                throw new Exception("缺少必要参数！");
            }
            service.SaveWorkZdSP(map);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }

    }

    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFile(MultipartFile file) {
        try {
            PageData map = getPageData();
            if (!map.containsKey("empId")) {
                //throw new Exception("缺少用户信息，请登陆系统");
                map.put("empId", 1);
            }

            Integer empId = Common.toInt(map.get("empId"));
            MTemp memp = empService.single(empId);
            HttpServletRequest request = this.getRequest();
            String filePath = "";
            String resPath = "";
            if (null != file) {
                String fileName = file.getOriginalFilename();
//                String path = request.getSession().getServletContext().getRealPath("/") + "upload/";
//                System.out.println("path  = " + path);
//                // 判断目录是否存在，不存在则创建目录
//                File pFile = new File(path);
//                if (!pFile.exists()) {
//                    pFile.mkdir();
//                }
//
//                path += memp.getEMP_NO() + "/";
//                File userAccountFile = new File(path);
//                if (!userAccountFile.exists()) {
//                    userAccountFile.mkdir();
//                }
//                String ext = fileName.substring(fileName.lastIndexOf("."));
//                String newFileName = UUID.randomUUID() +ext;
//                filePath = path + newFileName;
                String ejpath = memp.getEMP_NO() + "/";
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                Date date = new Date();
                String strSdate = sdf.format(date);
                strSdate = strSdate + "/";
                filePath = Common.CreateFilePath(request, ejpath, strSdate, fileName);

                file.transferTo(new File(filePath));
                String tempName = filePath.substring(filePath.lastIndexOf("/") + 1);

                resPath = "/upload/" + ejpath + strSdate + tempName;


            }
            return LResult.Success(resPath).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }

    }

    @ResponseBody
    @RequestMapping(value = "/uploadFiles")
    public String uploadFiles(MultipartFile[] files) {
        try {
            PageData map = getPageData();
            if (!map.containsKey("empId")) {
                throw new Exception("缺少用户信息，请登陆系统");
                //map.put("empId", 1);
            }

            Integer empId = Common.toInt(map.get("empId"));
            MTemp memp = empService.single(empId);
            HttpServletRequest request = this.getRequest();
            String resStr = "";
            String ejpath = memp.getEMP_NO() + "/";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String strSdate = sdf.format(date);
            strSdate = strSdate + "/";
            if (null != files) {


                for (MultipartFile file :
                        files) {
                    String filePath = "";
                    String fileName = file.getOriginalFilename();
                    filePath = Common.CreateFilePath(request, ejpath, strSdate, fileName);
                    file.transferTo(new File(filePath));
                    String tempName = filePath.substring(filePath.lastIndexOf("/") + 1);

                    resStr = "/upload/" + ejpath + strSdate + tempName + ",";
                }
            }
            resStr = resStr.substring(0, resStr.length() - 1);
            System.out.println(resStr);
            return LResult.Success(resStr).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("initList")
    public String initList(int appId) {
        try {
            Map<String, Object> map = service.initList(appId);
            return LResult.Success(map).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("initEdit")
    public String initEdit(int appId) {
        try {
            Map<String, Object> map = service.initEdit(appId);
            return LResult.Success(map).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }


}
